package com.tea.service.impl;

import com.tea.constant.CouponConstant;
import com.tea.constant.MessageConstant;
import com.tea.constant.StatusConstant;
import com.tea.dto.GetCouponDTO;
import com.tea.entity.Coupon;
import com.tea.entity.UserCoupon;
import com.tea.exception.CouponBusinessException;
import com.tea.mapper.CouponMapper;
import com.tea.mapper.UserCouponMapper;
import com.tea.service.UserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserCouponServiceImpl implements UserCouponService {
    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    @Transactional
    public void distributeCoupon(GetCouponDTO getCouponDTO) {




        //通过调用couponIfGet（是否已经领取该优惠券函数）来抛出异常
        if (couponIfGet(getCouponDTO.getUserId(),getCouponDTO.getCouponId() ) ) {
            throw new CouponBusinessException(MessageConstant.COUPON_CLAIMED);
        }


        //如果优惠券为空和不可用 checkCouponIfAvailable函数会返回一个false
        if (!checkCouponIfAvailable(getCouponDTO.getCouponId() ) ) {
            throw new CouponBusinessException(MessageConstant.COUPON_NOT_AVAILABLE);
        }

       //条件查询优惠券表，
        Coupon coupon=new Coupon();
        coupon.setId(getCouponDTO.getCouponId());
        List<Coupon>couponList=couponMapper.list(coupon);

        // 保存用户优惠券
        UserCoupon userCoupon=new UserCoupon();
        userCoupon.setUserId(getCouponDTO.getUserId());
        userCoupon.setCouponId(getCouponDTO.getCouponId());
        userCoupon.setStatus(CouponConstant.NOT_USED);
        userCoupon.setAcquireTime(new Date());
        userCoupon.setExpireTime(calculateExpireTime(couponList.get(0)));
        userCouponMapper.insert(userCoupon);

    }



    public Date calculateExpireTime(Coupon coupon) {
        // 计算过期时间逻辑
        // ...

        return coupon.getExpireTime();
    }


    //检查是否用户已经领取该优惠券
    public boolean couponIfGet(Long userId,Long couponId){
        String key ="user" +  "_"  + "coupon"  +  "_"  +userId +  "_"  +  couponId;
        UserCoupon userCoupon=new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(couponId);

        //查看redis缓存中是否有缓存
        if (redisTemplate.opsForValue().get(key) != null) {
            return true;
        }

        //查看数据库是否有领取记录
        else if(userCouponMapper.list(userCoupon) !=null && userCouponMapper.list(userCoupon).size() != 0){
            return true;
        }

        return false;

    }


    //检查优惠券是否有效
    public boolean checkCouponIfAvailable(Long couponId){

        Coupon coupon=new Coupon();
        coupon.setId(couponId);
        List<Coupon>couponList=couponMapper.list(coupon);
        //如果优惠券不等于空 或者 优惠券状态为不为0（未使用）则弹出异常：优惠券是无效的
        if (couponList == null && couponList.size() == 0|| couponList.get(0).getStatus() !=0) {
            return false;
        }
        return true;

    }

    //计算使用优惠券之后的Amount
    public BigDecimal useCountAmount(BigDecimal Amount,Long couponId){

        Coupon coupon = new Coupon();
        coupon.setId(couponId);
        List<Coupon> couponList=couponMapper.list(coupon);

        coupon=couponList.get(0);
        BigDecimal calculateAmount=new BigDecimal(0.12);
        System.out.println("调用useCountAmount函数："+couponList.get(0).getCode());
        switch (coupon.getType()){
            case 0:
                System.out.println("这是一个满减优惠券");
                //如果订单总额（Amount）大于优惠券中的满减标准（MinOrderAmount）则用订单总额减去折扣金额（DiscountValue）
                if(Amount.compareTo(coupon.getMinOrderAmount()) != -1)
                {
                    calculateAmount=Amount.subtract(coupon.getDiscountValue());
                }

                else{
                    calculateAmount=Amount;
                }
                break;

            case 1:
                System.out.println("这是折扣优惠券");
                calculateAmount=Amount.multiply(coupon.getDiscountValue());
                break;

            case 2:
                System.out.println("这是立刻减优惠券");
                calculateAmount=Amount.subtract(coupon.getDiscountValue());
                break;
        }
        return calculateAmount;
    }

}
